package com.shenzhen.horselive.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.AuctionDetailsAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AuctionDetailsHeadBean;
import com.shenzhen.horselive.beans.AuctionDetailsRecordList;
import com.shenzhen.horselive.databinding.ActivityAuctionDetailsBinding;
import com.shenzhen.horselive.databinding.HeadAuctionDetailsBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.utils.TimeUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 竞拍中的城市
 */
public class AuctionDetailsActivity extends AppBarActivity {

    CityPickerView mPicker=new CityPickerView();
    ActivityAuctionDetailsBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAuctionDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mPicker.init(this);
        areaCode =  getIntent().getStringExtra("id");
        setStyleRed();
        setTitle("竞拍详情");
        initViews();
//        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    String areaCode;
    CountDownTimer   countDownTimer;
    private void initData() {
        if (areaCode==null)
            return;
        //获取头部信息
        ApiFactory.getApiService().auctionHeadDetails(User.get().getMyInfo().getToken(),areaCode)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AuctionDetailsHeadBean>(this) {
                    @Override
                    protected void onNextInActive(AuctionDetailsHeadBean auctionDetailsHeadBean) {
                        if (auctionDetailsHeadBean.isSuccess())
                        {
                            if (headbinding!=null)
                            {
//                                0待开放 1第一次竞价中 2第二次竞价中 3流拍中 4已锁定 （1,2,3状态都为竞拍中）
                                int  type =  auctionDetailsHeadBean.getData().getStatus();
                               if (type==0||type==4)
                               {
                                   MyCityLordActivity.start(getContext(),auctionDetailsHeadBean.getData().getAreaCode());
                                   finish();
                               }
                               else
                               {
                                //城市名字
                                headbinding.tvAddr.setText(auctionDetailsHeadBean.getData().getAreaName());
                                //上任城主收益
                                headbinding.tvValue.setText(formatFuckingNumber(auctionDetailsHeadBean.getData().getLastProfit())+"(蜂值)");
                               //起拍价格
                                headbinding.tvValue1.setText(auctionDetailsHeadBean.getData().getStartPrice()+"(蜂值)");
                                //剩余的竞拍时间
//                                headbinding.tvValue2.setText(auctionDetailsHeadBean.getData().getResidueAuctionTime());
                                  countDownTimers(auctionDetailsHeadBean.getData().getResidueAuctionTime());
                                //获取的竞价列表
                                  getRecordList(auctionDetailsHeadBean.getData().getAuctionSerialNum());
                               }
                            }
                        }
                    }
                });


    }

    //显示倒计时控件
    private void countDownTimers(String time) {
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer =null;
        }
        //开始新的计算时间

        if (countDownTimer==null)
        {
            countDownTimer= new CountDownTimer(Long.parseLong(time)*1000-System.currentTimeMillis(),1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    headbinding.tvValue2.setText(TimeUtils.formatDuring(millisUntilFinished));
                }

                @Override
                public void onFinish() {
                    //这里刷新时间
                    initData();
                }
            };
            countDownTimer.start();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    private void   getRecordList(String  id)
    {
        //获取竞价列表
        ApiFactory.getApiService().auctionDetailsRecordList(User.get().getMyInfo().getToken()
                ,id).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AuctionDetailsRecordList>(this) {
                    @Override
                    protected void onNextInActive(AuctionDetailsRecordList auctionDetailsRecordList) {
                        if (auctionDetailsRecordList.isSuccess())
                        {
                            headbinding.tvText1.setText(String.format("竞拍记录(%s条)",auctionDetailsRecordList.getData().size()+""));
                            adapter.setNewInstance(auctionDetailsRecordList.getData());
                        }
                    }
                });
    }
    AuctionDetailsAdapter   adapter;
    private void initViews() {
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
          adapter  = new AuctionDetailsAdapter(R.layout.item_auction_details);
        binding.recyclerview.setAdapter(adapter);
        adapter.addHeaderView(getHead());
        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(AuctionDetailsActivity.this,PayAuctionCityActivity.class));
                if (areaCode==null)
                    return;
                PayAuctionCityActivity.start(AuctionDetailsActivity.this,areaCode);
            }
        });

        binding.btOtherCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCityPick();
            }
        });

        int  type = getIntent().getIntExtra("type",0);
        if (type==1)
        {
            binding.btOtherCity.setVisibility(View.VISIBLE);
        }
        else
        {
            binding.btOtherCity.setVisibility(View.GONE);
        }



    }
    HeadAuctionDetailsBinding  headbinding;
    private View getHead() {
        headbinding = HeadAuctionDetailsBinding.inflate(getLayoutInflater());
        return  headbinding.getRoot();
    }






    //打开城市选择器
    private void openCityPick() {
//        AreaPicker areaPicker = new AreaPicker();
//        areaPicker.setListener(new AreaPicker.AreaPickerListener() {
//            @Override
//            public void onPicked(String province, String city) {
//                binding.tvChooseCity.setText(province+""+city);
//            }
//        });
//        areaPicker.show(getSupportFragmentManager());

        //监听选择点击事件及返回结果
//添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        CityConfig cityConfig = new CityConfig.Builder().build();
        mPicker.setConfig(cityConfig);
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                //更新数据
                areaCode =district.getId();
                initData();
            }
            @Override
            public void onCancel() {

            }
        });

        //显示
        mPicker.showCityPicker( );
    }


    /**
     *
     * @param context
     * @param id  城市areaCode
     */
    public static void start(Context context,String  id) {
        Intent starter = new Intent(context, AuctionDetailsActivity.class);
        starter.putExtra("id",id);
        context.startActivity(starter);
    }

    /**
     *
     * @param context
     * @param id  城市areaCode
     * @param type    1竞拍大厅来的
     */
    public static void start(Context context,String  id,int  type) {
        Intent starter = new Intent(context, AuctionDetailsActivity.class);
        starter.putExtra("id",id);
        starter.putExtra("type",type);
        context.startActivity(starter);
    }


}